import React, {useState} from "react"
import {Checkbox, Form, Modal, ModalProps, Row} from "antd";
import tableColumnSelectStore, {RememberedColumnCache} from "../store/TableColumnSelectStore";
import {goodsTableColumnNames} from "./GoodsTable";
import {cache} from "browserslist";

export interface TableColumnSelectModalProps extends ModalProps{
    availableColumns: string[];
    onConfirm:(fields:string[])=>Promise<void>
    cacheKey:keyof  RememberedColumnCache
}

const TableColumnSelectModal: React.FC<TableColumnSelectModalProps> = (props) => {
    let [form] = Form.useForm();
    const [loading,setLoading] = useState(false)
    const [remembered,setRemembered] = useState(false)
    return (
        <>
            <Modal {...props} okText={"导出"} title={"选择需要的列"} onOk={_ => {
                form.submit()
            }} confirmLoading={loading}>
                <Form form={form} initialValues={{columns:tableColumnSelectStore.cache[props.cacheKey]??goodsTableColumnNames}} onFinish={async (values) => {
                    setLoading(true)
                    try {
                        let columns = values.columns as string[];
                        if(remembered) {
                            tableColumnSelectStore.cache = {
                                ...tableColumnSelectStore.cache,
                                [props.cacheKey]:columns,
                            }
                        }
                        props.onConfirm && (await props.onConfirm(columns))
                    } finally {
                        setLoading(false)
                    }
                }}>
                    <Form.Item required={true} rules={[{required:true,message:'请至少选择一项'}]} name={"columns"}>
                        <Checkbox.Group name={"columns"}>
                            {props.availableColumns.map((item) => <Checkbox key={item} value={item}>{item}</Checkbox>)}
                        </Checkbox.Group>
                    </Form.Item>
                    <Row style={{marginTop:24}}>
                        <div style={{flexGrow:1}}></div>
                        <Checkbox value={remembered} onChange={(e) => setRemembered(e.target.checked)}>记住本次选择</Checkbox>
                    </Row>
                </Form>
            </Modal>
        </>
    )
}

export default TableColumnSelectModal
